package com.imgo.max.experience.service;


import java.sql.Timestamp;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.imgo.max.artist.dto.DevoteInfo;
import com.imgo.max.common.dto.ResultDO;
import com.imgo.max.common.util.ObjectUtil;

@Component
public class ExperienceMessageServiceImpl implements ExperienceMessageService {
	
    static Logger logger = LoggerFactory.getLogger(ExperienceMessageServiceImpl.class);

    String EXPERIENCE_TAG = "experience";
    
    String DREAM_FUND_TAG = "dreamFund";

    @Resource
    ProducerBean producer;
    
    @Resource
    ProducerBean fundProducer;

    @Value("#{configProperties['topic']}")
    String topic;
    
    @Value("#{configProperties['fundTopic']}")
    String fundTopic;
    
    /**
     * 用户消息计数，重启后数据会丢失一部分
     */
    ConcurrentHashMap<String, AtomicInteger> userMsgCounter = new ConcurrentHashMap<String, AtomicInteger>();
    
    /**
     * 10条消息累计1经验
     * 由于一个用户基本不会同时发出多个聊天消息，所以此方法没有采用线程同步
     * @param fromUid 发送消息的用户
     */
    @Override
    public void addMsgExpr(String fromUid)
    {
    	AtomicInteger msgCount = userMsgCounter.get(fromUid);
    	if (msgCount == null)
    	{
    		userMsgCounter.put(fromUid, new AtomicInteger(1));
    	}
    	else
    	{
    		int count = msgCount.addAndGet(1);
    		if (count >= 10)
    		{
    			DevoteInfo devote = new DevoteInfo();
    			devote.setArtistUid("");
    			devote.setUid(fromUid);
    			devote.setDevoteValue(1); //增加的经验
    			logger.error("用户{}累计发送10条消息，经验增加1", fromUid);
    			// 贡献值来源 － 0:加粉丝 1:礼物 2:守护 3:直播时长 4:观看人数 5:每次直播峰值 6发消息
    			devote.setType(6);
    			devote.setTime(new Timestamp(System.currentTimeMillis()));
    			Message message = new Message(topic, EXPERIENCE_TAG, ObjectUtil.toByteArray(devote));
    			try
    			{
    				SendResult send = producer.send(message);
    				if (count > 10)
    				{
    					userMsgCounter.put(fromUid, new AtomicInteger(count -10));
    				}else
    				{
    					userMsgCounter.remove(fromUid);
    				}
    			}
    			catch(Exception e)
    			{
    				logger.error(e.getMessage(), e);
    				logger.error("发送涨经验消息失败");
    			}

    		}
    	}
    }

    /**
     * 只针对练习生的部分经验的消息，比如直播时长，直播峰值人数
     * 购买礼物涨经验(用户和练习生都涨经验的情况)不走此消息，而是直接消费人气的消息来涨经验
     * 
     */
    @Override
    public ResultDO<Void> updateExperience(byte[] devote) {
        try {

            Message message = new Message(topic, EXPERIENCE_TAG, devote);
            SendResult send = producer.send(message);
            logger.info("send message Id:{}", send.getMessageId());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ResultDO objectResultDO = new ResultDO<>();
            objectResultDO.setSuccess(false);
            return objectResultDO;
        }
        return new ResultDO();
    }
    
    /**
     * 只针对练习生的梦想基金
     * 购买礼物涨经验(用户和练习生都涨经验)不走此消息
     */
    @Override
    public ResultDO<Void> updateDreamFund(byte[] devote) {
        try {

            Message message = new Message(fundTopic, DREAM_FUND_TAG, devote);
            SendResult send = fundProducer.send(message);
            logger.info("send message Id:{}", send.getMessageId());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ResultDO objectResultDO = new ResultDO<>();
            objectResultDO.setSuccess(false);
            return objectResultDO;
        }
        return new ResultDO();
    }

}
